package com.czy.owner.ui.store;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.czy.owner.R;
import com.czy.owner.alipay.PayResult;
import com.czy.owner.db.UserHelper;
import com.czy.owner.global.Constants;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.setting.ForgetPaidPasswordActivity;
import com.czy.owner.utils.CashierInputFilter;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.wxapi.WXPayEntryActivity;
import com.input.password.ui.InputPwdView;
import com.input.password.ui.MyInputPwdUtil;
import com.input.password.ui.PaidErrorDialog;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by wangayng on 2016/10/11 0011.
 * 付款界面
 */
public class PaidActivity extends BaseActivity {
    @BindView(R.id.et_jine)
    EditText etJine;//输入金额
    @BindView(R.id.img_cancle)
    ImageView imgCancle; //取消
    @BindView(R.id.tv_use_yue)
    TextView tvUseYue;//可用余额
    @BindView(R.id.cb_yue)
    CheckBox cbYue;//使用余额CheckBox
    @BindView(R.id.cb_zhifubao)
    CheckBox cbZhiFuBao;//支付宝CheckBox
    @BindView(R.id.cb_weixin)
    CheckBox cbWeiXin;//微信CheckBox
    @BindView(R.id.tv_sdk_paid_tip)
    TextView tvSdkPaidTip;
    private static final int SDK_PAY_FLAG = 1;//支付
    private String seletPaidType = "aliPay";
    //    private String useStoreBalance = "false";
    private String paidJinE = "0";
    private double realityPaid = 0.00; //实际支付
    private double storeBalance = 0.00;

    private MyInputPwdUtil myInputPwdUtil;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        paidSuccessInfo();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        PhoneUtils.ShowToastMessage(PaidActivity.this, "支付失败");
                    }
                    break;
                }


            }
        }

    };


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_paid;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.package_paid);
        RxBus.getDefault().register(this);
        etJine.addTextChangedListener(new EditChangedListener());
        etJine.setSelection(etJine.getText().toString().length());
        InputFilter[] filters = {new CashierInputFilter(9), new InputFilter.LengthFilter(9)};
        etJine.setFilters(filters);
        myInputPwdUtil = new MyInputPwdUtil(this);
        myInputPwdUtil.getMyInputDialogBuilder().setAnimStyle(R.style.ActionSheetDialogAnimation);
        myInputPwdUtil.setListener(new InputPwdView.InputPwdListener() {
            @Override
            public void hide() {
                myInputPwdUtil.hide();
            }

            @Override
            public void forgetPwd() {
                startActivity(new Intent(PaidActivity.this, ForgetPaidPasswordActivity.class));
            }

            @Override
            public void finishPwd(String pwd) {
                bannceVerifyPayPassword(pwd);
            }
        });
        userStoreBalance();
    }

    @Override
    protected void updateViews() {

    }


    class EditChangedListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (tvSdkPaidTip.getVisibility() == View.VISIBLE) {
                tvSdkPaidTip.setVisibility(View.GONE);
            }

            if (cbYue.isChecked()) {
                cbYue.setChecked(false);
                cbZhiFuBao.setChecked(true);
            }

            if (etJine.getText().toString().trim().length() > 0) {
                imgCancle.setVisibility(View.VISIBLE);
            } else {
                imgCancle.setVisibility(View.GONE);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            paidJinE = etJine.getText().toString().trim();
            if (paidJinE.length() > 0) {
                imgCancle.setVisibility(View.VISIBLE);
            } else {
                imgCancle.setVisibility(View.GONE);
                if (tvSdkPaidTip.getVisibility() == View.VISIBLE) {
                    tvSdkPaidTip.setVisibility(View.GONE);
                    if (cbYue.isChecked()) {
                        cbYue.setChecked(false);
//                        useStoreBalance = "false";
                    }
                }


            }

        }
    }

    //余额支付
    @OnClick(R.id.cb_yue)
    public void cbYuEOnClick(View view) {
        paidJinE = etJine.getText().toString().trim();
        if (TextUtils.isEmpty(paidJinE)) {
            PhoneUtils.ShowToastMessage(PaidActivity.this, "请输入付款金额");
            cbYue.setChecked(false);
            return;
        } else {
            double userInputJinE = Double.valueOf(paidJinE);
            realityPaid = storeBalance - userInputJinE;
            if (cbYue.isChecked()) {
                if (realityPaid >= 0) {  //当门店余额大于等于实际支付余额时
                    cbZhiFuBao.setChecked(false);
                    cbWeiXin.setChecked(false);
                    cbYue.setChecked(true);
                    tvSdkPaidTip.setVisibility(View.GONE);
                } else {
                    tvSdkPaidTip.setVisibility(View.VISIBLE);
                    tvSdkPaidTip.setText("余额可支付¥" + String.format("%.2f", storeBalance) + ",还需第三方支付¥" + String.format("%.2f", Math.abs(realityPaid)));
                }
//                useStoreBalance = "true";
            } else {
                tvSdkPaidTip.setVisibility(View.GONE);
                if (realityPaid >= 0) {  //当门店余额大于等于实际支付余额时
                    cbYue.setChecked(true);
                }

//                useStoreBalance = "false";
            }
        }


    }

    //支付宝支付
    @OnClick(R.id.cb_zhifubao)
    public void cbZhiFuBaoOnClick(View view) {
        if (tvSdkPaidTip.getVisibility() == View.VISIBLE && !cbWeiXin.isChecked()) {
            cbZhiFuBao.setChecked(true);
            return;
        }

        if (cbZhiFuBao.isChecked()) {
            cbWeiXin.setChecked(false);
            seletPaidType = "aliPay";
            if (realityPaid >= 0 && cbYue.isChecked() == true) {
                cbYue.setChecked(false);
            }
        } else {
            seletPaidType = "11";
            cbZhiFuBao.setChecked(true);
        }


    }

    //微信支付
    @OnClick(R.id.cb_weixin)
    public void cbWeiXinOnClick(View view) {

        if (tvSdkPaidTip.getVisibility() == View.VISIBLE && !cbZhiFuBao.isChecked()) {
            cbWeiXin.setChecked(true);
            return;
        }

        if (cbWeiXin.isChecked()) {
            cbZhiFuBao.setChecked(false);
            seletPaidType = "wxPay";
            if (realityPaid >= 0 && cbYue.isChecked() == true) {
                cbYue.setChecked(false);
            }
        } else {
            seletPaidType = "22";
            cbWeiXin.setChecked(true);
        }


    }

    //    支付宝调用
    private void aliPayPaid(final String data) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(PaidActivity.this);
                // 调用支付接口，获取支付结果
                Map<String, String> result = alipay.payV2(data, true);
                MyLog.e("yang", "result==" + result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    @OnClick(R.id.img_cancle)
    public void imgClearOnClick(View view) {
        etJine.setText("");
    }


    //确认支付
    @OnClick(R.id.btn_sure_paid)
    public void btnSureOnClick(View view) {
        String inputMoney = etJine.getText().toString().trim();
        if (TextUtils.isEmpty(inputMoney)) {
            PhoneUtils.ShowToastMessage(PaidActivity.this, "请输入付款金额");
            return;
        } else {
            if (cbYue.isChecked()) {
                myInputPwdUtil.show();
            } else {
                payAmount(inputMoney);
            }
        }
    }

    private void bannceVerifyPayPassword(String payPassword) {
        String url = Constants.APP_API_BASE + Constants.OWN_VERIFYPAYPASSWORD;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(PaidActivity.this).getSession());
        params.addBodyParameter("payPassword", payPassword);
        params.addBodyParameter("userId", UserHelper.getInstance().getUserInfoModel(PaidActivity.this).getUserId() + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "onSuccess==" + result);

                String exp = JsonUtil.getJsonValuesString(result, "exp");
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
                int count = JsonUtil.getJsonValuesInt(result, "data");

                if (flag) {
                    String inputMoney = etJine.getText().toString().trim();
                    myInputPwdUtil.hide();
                    payAmount(inputMoney);
                } else {
                    switch (count) {
                        case 1:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paidPswErrorDialog(PaidActivity.this, myInputPwdUtil);
                            break;
                        case 2:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paidPswErrorDialog(PaidActivity.this, myInputPwdUtil);
                            break;
                        case 3:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paid30AfterDialog(PaidActivity.this, exp);
                            break;
                        case -1:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paid30AfterDialog(PaidActivity.this, exp);
                            break;
                    }
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }

    private void userStoreBalance() {
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_PRE_QUICK_PAYMENT;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        params.addBodyParameter("storeId", SharedPreferencesUtils.getParam(PaidActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String data = PhoneUtils.checkResponseFlag(PaidActivity.this, result);
                if (data != null) {
                    storeBalance = JsonUtil.getJsonValuesDouble(data, "storeBalance");
                    tvUseYue.setText("¥" + String.format("%.2f", storeBalance));
                    if (storeBalance == 0) {
                        cbYue.setClickable(false);
                    } else {
                        cbYue.setClickable(true);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }


            @Override
            public void onFinished() {

            }
        });
    }

    private void payAmount(final String inputMoney) {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_QUICKPAYMENT;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        params.addBodyParameter("storeId", SharedPreferencesUtils.getParam(PaidActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        params.addBodyParameter("payAmount", inputMoney + "");
        if (seletPaidType.equals("aliPay") || seletPaidType.equals("wxPay")) {
            params.addBodyParameter("payType", seletPaidType);
        }
        params.addBodyParameter("useStoreBalance", cbYue.isChecked() + "");
        MyLog.e("yang", "params==" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "支付定金onSuccess==" + result);
                String data = PhoneUtils.checkResponseFlag(PaidActivity.this, result);
                if (data.equals("")) {
                    paidSuccessInfo();
                } else {
                    if (seletPaidType.equals("aliPay")) {
                        aliPayPaid(data);
                    } else if (seletPaidType.equals("wxPay")) {
                        if (isWXAppInstalledAndSupported()) {
                            WXPayEntryActivity.wxPayPaidStart(PaidActivity.this, data, "付款成功");
                        } else {
                            PhoneUtils.ShowToastMessage(PaidActivity.this, getString(R.string.isInstallwx));
                        }
                    }
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }

    //判断是否安装微信客户端
    public boolean isWXAppInstalledAndSupported() {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(WXPayEntryActivity.APP_ID);
        boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled() && msgApi.isWXAppSupportAPI();
        return sIsWXAppInstalledAndSupported;
    }

    private void paidSuccessInfo() {
        PhoneUtils.ShowToastMessage(PaidActivity.this, "付款成功");
        RxBus.getDefault().post(Constants.PAYMENT_SECCESS, new CommonEvent("付款成功"));
    }

    @Subscribe(code = Constants.PAYMENT_SECCESS, threadMode = ThreadMode.MAIN)
    public void onPaymentSuccess(CommonEvent event) {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(PaidActivity.this);
    }
}
